package com.aek.aekdroid.data;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.aek.aekdroid.MyLog;
import com.aek.aekdroid.data.Match.Detail;

public abstract class BasicData implements IDbConstants {
	public DbHelper dbHelper;
	public static final String TAG = "BasicData";

	public BasicData(Context context) {
		this.dbHelper = new DbHelper(context);
	}

	public void close() {
		this.dbHelper.close();
	}

	public void delete() {
		// Open Database
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		// Delete the data
		db.delete(IDbConstants.MATCHES_TABLE, null, null);
		// Close Database
		db.close();
	}

	protected void update(String table, ContentValues values, int id) {
		SQLiteDatabase db = this.dbHelper.getWritableDatabase();
		try {
			db.update(table, values, "_id=?", new String[] { String.valueOf(id) });
		} finally {
			db.close();
		}
	}

	protected void insertOrUpdate(String table, ContentValues values, ArrayList<Detail> details) {
		SQLiteDatabase db = this.dbHelper.getWritableDatabase();
		db.beginTransaction();
		try {
			try {
				MyLog.d(TAG, "Inserting new match");
				db.insertOrThrow(table, null, values);
				MyLog.d(TAG, "Inserted new match");
			} catch (SQLException ex) {
				MyLog.d(TAG, "Updating match");
				db.update(table, values, "_id=?", new String[] { values.getAsString("_id") });
				MyLog.d(TAG, "Updated new match");
			}
			MyLog.d(TAG, "Inserting details");
			for (Detail detail : details) {
				ContentValues detailValues = new ContentValues();
				detailValues.put(DETAILS_C_ID, detail._id);
				detailValues.put(DETAILS_C_MATCH_ID, detail.match_id);
				detailValues.put(DETAILS_C_MIN, detail.min);
				detailValues.put(DETAILS_C_TYPE, detail.type);
				detailValues.put(DETAILS_C_PLAYER, detail.player);
				detailValues.put(DETAILS_C_COMMENT, detail.comment);
				detailValues.put(DETAILS_C_SIDE, detail.side);
				detailValues.put(DETAILS_C_DELETED, detail.deleted);
				MyLog.i(TAG, "Insert or update on " + detailValues);
				try {
					MyLog.d(TAG, "Inserting new details");
					db.insertOrThrow(DETAILS_TABLE, null, detailValues);
					MyLog.d(TAG, "Inserted new details");
				} catch (SQLException ex) {
					MyLog.d(TAG, "Updating details");
					db.update(DETAILS_TABLE, detailValues, "_id=?", new String[] { detailValues.getAsString("_id") });
					MyLog.d(TAG, "Updated details");
				}
			}
			db.setTransactionSuccessful();
		} catch (Exception ex) {
			MyLog.e(TAG, "Failed to update the db ");
			ex.printStackTrace();
		} finally {
			db.endTransaction();
			db.close();
		}
	}
}
